package user.fragment;

import static user.fragment.AddressManagementActivity.API_URL;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.xfengshopping.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import LOGIN.login;
import cn.zzuli.citypicker.bean.CityInfo;
import cn.zzuli.citypicker.utils.CityListLoader;
import cn.zzuli.citypicker.widget.CityPickerBottomDialog;
import utils.TokenUtils;
import user.fragment.Address;

public class AddressEditActivity extends AppCompatActivity {

    // 控件声明
    private EditText nameEt, phoneEt, detailEt;
    private CheckBox defaultCb;
    private TextView saveText, addressTv, deleteText;
    private Address editAddress;
    private CityPickerBottomDialog dialog;

    // 消息类型
    private static final int SAVE_SUCCESS = 1;
    private static final int SAVE_FAILED = 2;
    private static final int DELETE_SUCCESS = 3;
    private static final int DELETE_FAILED = 4;
    private static final int UNAUTHORIZED = 401;

    // 主线程处理器
    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SAVE_SUCCESS:
                    handleSaveSuccess();
                    break;
                case SAVE_FAILED:
                    Toast.makeText(AddressEditActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case DELETE_SUCCESS:
                    handleDeleteSuccess();
                    break;
                case DELETE_FAILED:
                    Toast.makeText(AddressEditActivity.this, (String) msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case UNAUTHORIZED:
                    handleUnauthorized();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.address_edit);
        initializeComponents();
    }

    private void initializeComponents() {
        initViews();
        initCityPicker();
        initData();
        setupListeners();
    }

    @SuppressLint("WrongViewCast")
    private void initViews() {
        nameEt = findViewById(R.id.name_et);
        phoneEt = findViewById(R.id.phone_et);
        addressTv = findViewById(R.id.address_tv);
        detailEt = findViewById(R.id.detail_et);
        defaultCb = findViewById(R.id.default_cb);
        saveText = findViewById(R.id.save_text);
        deleteText = findViewById(R.id.delete_text);
        findViewById(R.id.back_btn).setOnClickListener(v -> finish());
    }

    private void initCityPicker() {
        CityListLoader.getInstance().init(this);
        dialog = new CityPickerBottomDialog(this);
        configureCityPickerDialog();
    }

    private void configureCityPickerDialog() {
        dialog.setTitle("选择地址");
        dialog.setDimAmount(0.5f);
        dialog.setOnSubmitClickListener((province, city, district) -> {
            addressTv.setText(String.format("%s %s %s",
                    province.name, city.name, district.name));
            dialog.dismiss();
        });
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent.hasExtra("address")) {
            handleEditMode(intent);
        } else {
            handleAddMode();
        }
    }

    private void handleEditMode(Intent intent) {
        editAddress = (Address) intent.getSerializableExtra("address");
        if (editAddress != null) {
            deleteText.setVisibility(View.VISIBLE);
            populateFormData();
        }
    }

    private void populateFormData() {
        nameEt.setText(editAddress.name);
        phoneEt.setText(editAddress.phone);
        defaultCb.setChecked(editAddress.isDefault);

        String[] addressParts = editAddress.address.split(" ", 4);
        if (addressParts.length == 4) {
            addressTv.setText(String.format("%s %s %s",
                    addressParts[0], addressParts[1], addressParts[2]));
            detailEt.setText(addressParts[3]);
        }
    }

    private void handleAddMode() {
        deleteText.setVisibility(View.GONE);
        editAddress = new Address(-1, "", "", "", false);
    }

    private void setupListeners() {
        saveText.setOnClickListener(v -> validateAndSave());
        deleteText.setOnClickListener(v -> showDeleteConfirmation());
        findViewById(R.id.address_select_layout).setOnClickListener(v -> dialog.show());
    }

    private void validateAndSave() {
        if (!validateRequiredFields()) return;

        String[] regions = addressTv.getText().toString().trim().split(" ");
        if (regions.length != 3) {
            showValidationError("请选择完整的省市区");
            return;
        }

        try {
            JSONObject requestBody = buildRequestBody(regions);
            new Thread(() -> executeSaveRequest(requestBody)).start();
        } catch (JSONException e) {
            sendErrorMessage(SAVE_FAILED, "参数构建失败");
        }
    }

    private boolean validateRequiredFields() {
        if (TextUtils.isEmpty(nameEt.getText())){
            showValidationError("请输入姓名");
            return false;
        }
        if (TextUtils.isEmpty(phoneEt.getText())) {
            showValidationError("请输入手机号");
            return false;
        }
        if (TextUtils.isEmpty(detailEt.getText())) {
            showValidationError("请输入详细地址");
            return false;
        }
        return true;
    }

    private void showValidationError(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    private JSONObject buildRequestBody(String[] regions) throws JSONException {
        JSONObject requestBody = new JSONObject();
        requestBody.put("addressId", editAddress.id);
        requestBody.put("userName", nameEt.getText().toString().trim());
        requestBody.put("userPhone", phoneEt.getText().toString().trim());
        requestBody.put("provinceName", regions[0]);
        requestBody.put("cityName", regions[1]);
        requestBody.put("regionName", regions[2]);
        requestBody.put("detailAddress", detailEt.getText().toString().trim());
        requestBody.put("defaultFlag", defaultCb.isChecked() ? 1 : 0);
        requestBody.put("userId", parseUserIdFromToken());
        return requestBody;
    }

    private int parseUserIdFromToken() {
        // 实际应从Token解析用户ID
        return 1;
    }

    private void executeSaveRequest(JSONObject requestBody) {
        HttpURLConnection connection = null;
        try {
            connection = createConnection();
            sendRequestData(connection, requestBody);
            processSaveResponse(connection);
        } catch (Exception e) {
            handleNetworkError(e);
        } finally {
            if (connection != null) connection.disconnect();
        }
    }

    private HttpURLConnection createConnection() throws Exception {
        URL url = new URL(API_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("PUT");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("token", TokenUtils.getToken(this));
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        conn.setDoOutput(true);
        return conn;
    }

    private void sendRequestData(HttpURLConnection conn, JSONObject data) throws Exception {
        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = data.toString().getBytes("utf-8");
            os.write(input, 0, input.length);
        }
    }

    private void processSaveResponse(HttpURLConnection conn) throws Exception {
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            handleSuccessfulSave(conn);
        } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            handler.sendEmptyMessage(UNAUTHORIZED);
        } else {
            handleFailedSave(conn);
        }
    }

    private void handleSuccessfulSave(HttpURLConnection conn) throws Exception {
        String response = readInputStream(conn.getInputStream());
        JSONObject jsonResponse = new JSONObject(response);
        if (jsonResponse.getInt("resultCode") == 200) {
            handler.sendEmptyMessage(SAVE_SUCCESS);
        } else {
            sendErrorMessage(SAVE_FAILED, jsonResponse.getString("message"));
        }
    }

    private void handleFailedSave(HttpURLConnection conn) throws IOException {
        String error = "HTTP错误码: " + conn.getResponseCode();
        if (conn.getErrorStream() != null) {
            error += "\n" + readInputStream(conn.getErrorStream());
        }
        sendErrorMessage(SAVE_FAILED, error);
    }

    private void handleNetworkError(Exception e) {
        String errorMsg = "网络错误: " + e.getMessage();
        Log.e("AddressEdit", errorMsg, e);
        sendErrorMessage(SAVE_FAILED, errorMsg);
    }

    private void showDeleteConfirmation() {
        new AlertDialog.Builder(this)
                .setTitle("删除地址")
                .setMessage("确定要永久删除这个地址吗？")
                .setPositiveButton("删除", (d, w) -> executeDeleteRequest())
                .setNegativeButton("取消", null)
                .show();
    }

    private void executeDeleteRequest() {
        if (editAddress == null || editAddress.id == -1) {
            sendErrorMessage(DELETE_FAILED, "无效的地址ID");
            return;
        }

        new Thread(() -> {
            HttpURLConnection connection = null;
            try {
                connection = createDeleteConnection();
                processDeleteResponse(connection);
            } catch (Exception e) {
                handleDeleteError(e);
            } finally {
                if (connection != null) connection.disconnect();
            }
        }).start();
    }

    private HttpURLConnection createDeleteConnection() throws Exception {
        URL url = new URL(API_URL + "/" + editAddress.id);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("DELETE");
        conn.setRequestProperty("token", TokenUtils.getToken(this));
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);
        return conn;
    }

    private void processDeleteResponse(HttpURLConnection conn) throws IOException {
        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            handler.sendEmptyMessage(DELETE_SUCCESS);
        } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            handler.sendEmptyMessage(UNAUTHORIZED);
        } else {
            String error = "删除失败，错误码：" + responseCode;
            if (conn.getErrorStream() != null) {
                error += "\n" + readInputStream(conn.getErrorStream());
            }
            sendErrorMessage(DELETE_FAILED, error);
        }
    }

    private void handleDeleteError(Exception e) {
        String errorMsg = "删除失败: " + e.getMessage();
        Log.e("AddressEdit", errorMsg, e);
        sendErrorMessage(DELETE_FAILED, errorMsg);
    }

    private String readInputStream(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder response = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        return response.toString();
    }

    private void sendErrorMessage(int messageType, String error) {
        handler.sendMessage(handler.obtainMessage(messageType, error));
    }

    private void handleSaveSuccess() {
        Toast.makeText(this, "地址保存成功", Toast.LENGTH_SHORT).show();
        setResult(RESULT_OK);
        finish();
    }

    private void handleDeleteSuccess() {
        Toast.makeText(this, "地址删除成功", Toast.LENGTH_SHORT).show();
        setResult(RESULT_OK);
        finish();
    }

    private void handleUnauthorized() {
        runOnUiThread(() -> {
            Toast.makeText(this, "登录已过期，请重新登录", Toast.LENGTH_SHORT).show();
            TokenUtils.clearToken(this);
            startActivity(new Intent(this, login.class));
            finishAffinity();
        });
    }

    @Override
    public void onBackPressed() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        } else {
            super.onBackPressed();
        }
    }
}